<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="85px">
      <el-form-item label="计划编号" prop="planCode">
        <el-input
          v-model="queryParams.planCode"
          placeholder="请输入计划编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="计划名称" prop="planName">
        <el-input
          v-model="queryParams.planName"
          placeholder="请输入计划名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="巡检配置" prop="configId">
        <el-select v-model="queryParams.configId" placeholder="请选择巡检配置" clearable>
          <el-option
            v-for="item in configOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="计划状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择计划状态" clearable>
          <el-option label="停用" value="0" />
          <el-option label="启用" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="计划日期">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['sb:inspection-plan:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['sb:inspection-plan:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['sb:inspection-plan:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="planList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="计划编号" align="center" prop="planCode" />
      <el-table-column label="计划名称" align="center" prop="planName" :show-overflow-tooltip="true" />
      <el-table-column label="设备" align="center" prop="equipmentName" :show-overflow-tooltip="true" />
      <el-table-column label="巡检配置" align="center" prop="configName" :show-overflow-tooltip="true" />
      <el-table-column label="周期类型" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.cycleType === '1'" type="primary">每天</el-tag>
          <el-tag v-else-if="scope.row.cycleType === '2'" type="success">每周</el-tag>
          <el-tag v-else-if="scope.row.cycleType === '3'" type="warning">每月</el-tag>
          <el-tag v-else-if="scope.row.cycleType === '4'" type="info">每季度</el-tag>
          <el-tag v-else-if="scope.row.cycleType === '5'" type="danger">每年</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="巡检人" align="center" prop="inspectorName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['sb:inspection-plan:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['sb:inspection-plan:remove']"
          >删除</el-button>
          <el-dropdown trigger="click" @command="(command) => handleCommand(command, scope.row)">
            <span class="el-dropdown-link">
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="generate" icon="el-icon-plus">生成巡检单</el-dropdown-item>
              <el-dropdown-item command="viewRecords" icon="el-icon-document">查看巡检记录</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加/修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="850px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-divider content-position="left">基本信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="巡检配置" prop="configId">
              <el-select v-model="form.configId" placeholder="请选择巡检配置" filterable style="width: 100%;" @change="handleConfigChange">
                <el-option
                  v-for="item in configOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划名称" prop="planName">
              <el-input v-model="form.planName" placeholder="请输入计划名称" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="计划编号" prop="planCode">
              <div style="display: flex; align-items: center;">
                <div style="flex: 1; position: relative;">
                  <el-input v-model="form.planCode" placeholder="请输入计划编号" :disabled="autoGenerateCodes || title === '修改巡检计划'" />
                </div>
                <div style="margin-left: 10px; display: flex; align-items: center;">
                  <el-checkbox v-model="autoGenerateCodes" @change="handleAutoGenerateCodesChange" :disabled="title === '修改巡检计划'">自动生成</el-checkbox>
                  <el-button v-if="form.configId && title !== '修改巡检计划'" type="text" @click="forceGenerateCode" style="padding: 0 5px;">重新生成</el-button>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备" prop="equipmentId">
              <el-select v-model="form.equipmentId" placeholder="请选择设备" filterable style="width: 100%;" @change="handleEquipmentChange">
                <el-option
                  v-for="item in equipmentOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="执行人" prop="inspectorId">
              <el-input v-model="form.inspectorName" placeholder="请选择执行人" readonly @click.native="showUserSelect" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始日期" prop="startDate">
              <el-date-picker
                v-model="form.startDate"
                type="date"
                placeholder="请选择开始日期"
                value-format="yyyy-MM-dd"
                style="width: 100%;"
                @change="handleStartDateChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker
                v-model="form.endDate"
                type="date"
                placeholder="请选择结束日期"
                value-format="yyyy-MM-dd"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">巡检周期设置</el-divider>
        <el-row>
          <el-col :span="24">
            <el-form-item label="巡检周期" prop="cycleType">
              <div class="inspection-cycle-container">
                <el-tooltip class="help-icon" effect="dark" placement="top">
                  <div slot="content">
                    <p><strong>巡检周期使用说明：</strong></p>
                    <p>1. 选择频率类型（每天/每周/每月/自定义）</p>
                    <p>2. 根据频率类型设置具体执行时间</p>
                    <p>3. 每周：可选择周一至周日的任意组合</p>
                    <p>4. 每月：可选择每月几号执行</p>
                    <p>5. 自定义：可指定具体执行日期</p>
                    <p>系统将根据设置自动生成巡检计划</p>
                  </div>
                  <i class="el-icon-question"></i>
                </el-tooltip>

                <div class="cycle-type-selector">
                  <el-radio-group v-model="form.cycleType" @change="handleCycleTypeChange">
                    <el-radio label="1">每天</el-radio>
                    <el-radio label="2">每周</el-radio>
                    <el-radio label="3">每月</el-radio>
                  </el-radio-group>
                </div>

                <!-- 每天的配置选项 -->
                <div v-if="form.cycleType === '1'" class="cycle-config">
                  <span class="cycle-desc">每天执行一次巡检</span>
                </div>

                <!-- 每周的配置选项 -->
                <div v-if="form.cycleType === '2'" class="cycle-config">
                  <span class="cycle-label">选择执行日：</span>
                  <el-checkbox-group v-model="cycleConfig.weekdays" @change="updateCycleValue">
                    <el-checkbox label="1">周一</el-checkbox>
                    <el-checkbox label="2">周二</el-checkbox>
                    <el-checkbox label="3">周三</el-checkbox>
                    <el-checkbox label="4">周四</el-checkbox>
                    <el-checkbox label="5">周五</el-checkbox>
                    <el-checkbox label="6">周六</el-checkbox>
                    <el-checkbox label="0">周日</el-checkbox>
                  </el-checkbox-group>
                </div>

                <!-- 每月的配置选项 -->
                <div v-if="form.cycleType === '3'" class="cycle-config">
                  <span class="cycle-label">选择执行日期：</span>
                  <el-select 
                    v-model="cycleConfig.monthDays" 
                    multiple 
                    collapse-tags 
                    placeholder="请选择每月执行的日期"
                    @change="updateCycleValue"
                    style="width: 350px;">
                    <el-option 
                      v-for="day in 31" 
                      :key="day" 
                      :label="`${day}日`" 
                      :value="day">
                    </el-option>
                  </el-select>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        
      </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
    </el-dialog>
    
    <!-- 用户选择对话框 -->
    <el-dialog title="选择巡检人员" :visible.sync="userDialogVisible" width="800px" append-to-body>
      <!-- 搜索条件 -->
      <el-form :model="userQueryParams" ref="userQueryForm" :inline="true">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="userQueryParams.userName" placeholder="请输入用户名" clearable size="small" @keyup.enter.native="handleUserQuery" />
        </el-form-item>
        <el-form-item label="姓名" prop="nickName">
          <el-input v-model="userQueryParams.nickName" placeholder="请输入姓名" clearable size="small" @keyup.enter.native="handleUserQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleUserQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetUserQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 用户列表 -->
      <el-table v-loading="userListLoading" :data="userList" @row-click="handleUserRowClick" highlight-current-row>
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column label="用户ID" align="center" prop="userId" width="80" />
        <el-table-column label="用户名" align="center" prop="userName" width="100" />
        <el-table-column label="姓名" align="center" prop="nickName" width="100" />
        <el-table-column label="部门" align="center" width="150">
          <template slot-scope="scope">
            {{ scope.row.deptName || (scope.row.dept && scope.row.dept.deptName) || '未分配' }}
          </template>
        </el-table-column>
        <el-table-column label="手机号码" align="center" prop="phonenumber" width="120" />
        <el-table-column label="状态" align="center" width="80">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status === '0'" type="success">正常</el-tag>
            <el-tag v-else type="danger">禁用</el-tag>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="userTotal > 0"
        :total="userTotal"
        :page.sync="userQueryParams.pageNum"
        :limit.sync="userQueryParams.pageSize"
        @pagination="getUserList"
      />
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelUserSelect">取 消</el-button>
        <el-button type="primary" @click="confirmUserSelect">确 定</el-button>
      </div>
    </el-dialog>
    
    <!-- 查看巡检记录对话框 -->
    <el-dialog title="巡检记录列表" :visible.sync="recordsDialogVisible" width="1000px" append-to-body>
      <el-table v-loading="recordsLoading" :data="recordsList" border>
        <el-table-column label="巡检单号" prop="recordCode" width="120" align="center" />
        <el-table-column label="巡检日期" prop="inspectionDate" width="100" align="center" />
        <el-table-column label="巡检人员" prop="inspectorName" width="100" align="center" />
        <el-table-column label="巡检结果" align="center" width="80">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.result === '0'" type="success">正常</el-tag>
            <el-tag v-else type="danger">异常</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="80">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status === '0'" type="warning">待巡检</el-tag>
            <el-tag v-else-if="scope.row.status === '1'" type="primary">巡检中</el-tag>
            <el-tag v-else-if="scope.row.status === '2'" type="success">已完成</el-tag>
            <el-tag v-else-if="scope.row.status === '3'" type="info">已取消</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="开始时间" prop="startTime" width="150" align="center" />
        <el-table-column label="结束时间" prop="endTime" width="150" align="center" />
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleViewRecord(scope.row)"
            >查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="recordsDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInspectionPlan, getInspectionPlan, addInspectionPlan, updateInspectionPlan, deleteInspectionPlan, updateInspectionPlanStatus, generateInspectionRecord, generatePlanCode, checkPlanCodeUnique } from "@/api/sb/inspectionPlan";
import { listInspectionRecord } from "@/api/sb/inspectionRecord";
import { listEquipment } from "@/api/sb/equipment";
import { listInspectionConfig } from "@/api/sb/inspectionConfig";
import { listUser } from "@/api/system/user";

export default {
  name: "InspectionPlan",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 巡检计划表格数据
      planList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 巡检配置选项
      configOptions: [],
      // 设备选项
      equipmentOptions: [],
      // 用户选项
      userOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        planCode: null,
        planName: null,
        configId: null,
        equipmentId: null,
        status: null
      },
      // 表单参数
      form: {
        planId: null,
        planCode: null,
        planName: null,
        configId: null,
        configName: null,
        equipmentId: null,
        equipmentName: null,
        cycleType: "1",
        cycleValue: 1,
        cycleConfigJson: "",
        startDate: null,
        endDate: null,
        inspectorId: null,
        inspectorName: null,
        status: "0",
        autoGenerate: "1",
        deptId: null,
        deptName: null,
        remark: null
      },
      // 表单校验
      rules: {
        planName: [
          { required: true, message: "巡检计划名称不能为空", trigger: "blur" }
        ],
        configId: [
          { required: true, message: "巡检配置不能为空", trigger: "change" }
        ],
        equipmentId: [
          { required: true, message: "设备不能为空", trigger: "change" }
        ],
        cycleType: [
          { required: true, message: "周期类型不能为空", trigger: "change" }
        ],
        startDate: [
          { required: true, message: "开始日期不能为空", trigger: "blur" }
        ],
        endDate: [
          { required: true, message: "结束日期不能为空", trigger: "blur" }
        ],
        inspectorId: [
          { required: true, message: "巡检人员不能为空", trigger: "change" }
        ]
      },
      // 用户选择对话框
      userDialogVisible: false,
      userListLoading: false,
      userList: [],
      userTotal: 0,
      selectedUser: null,
      userQueryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: '',
        nickName: ''
      },
      // 巡检记录对话框
      recordsDialogVisible: false,
      recordsLoading: false,
      recordsList: [],
      currentPlanId: null,
      // 自动生成编码相关
      autoGenerateCodes: false,
      planCodeExists: false,
      
      // 周期配置对象
      cycleConfig: {
        weekdays: [], // 每周选择的星期几 [0-6]，0代表周日
        monthDays: [], // 每月选择的日期 [1-31]
        quarterMonths: [], // 每季度选择的月份 [1-3]
        quarterDays: [], // 每季度每月的日期
        yearMonths: [], // 每年选择的月份 [1-12]
        yearDays: [], // 每年每月的日期
        customDates: [] // 自定义选择的具体日期
      }
    };
  },
  created() {
    // 先获取配置和设备列表，再获取巡检计划列表
    Promise.all([
      this.getConfigList(),
      this.getEquipmentList()
    ]).then(() => {
    this.getList();
    }).catch(error => {
      console.error("初始化数据失败", error);
      this.getList();
    });
  },
  mounted() {
    // 检查是否需要刷新数据
    if (this.$route.query.refresh) {
      console.log("检测到刷新参数，重新加载数据");
      this.getList();
    }
  },
  watch: {
    // 监听路由变化，当从其他页面返回时刷新数据
    '$route'(to, from) {
      if (to.query.refresh) {
        console.log("路由变化，检测到刷新参数");
        this.$nextTick(() => {
          this.getList();
        });
      }
    }
  },
  methods: {
    /** 查询巡检计划列表 */
    getList() {
      this.loading = true;
      listInspectionPlan(this.queryParams).then(response => {
        this.planList = response.rows;
        this.total = parseInt(response.total) || 0;
        this.loading = false;

        // 如果configName为空但configId不为空，尝试匹配配置名称
        this.planList.forEach(plan => {
          if (!plan.configName && plan.configId) {
            const config = this.configOptions.find(c => c.value === plan.configId);
            if (config) {
              plan.configName = config.label;
            }
          }
          
          // 如果equipmentName为空但equipmentId不为空，尝试匹配设备名称
          if (!plan.equipmentName && plan.equipmentId) {
            const equipment = this.equipmentOptions.find(e => e.value === plan.equipmentId);
            if (equipment) {
              plan.equipmentName = equipment.label;
            }
          }
        });
      }).catch(error => {
        console.error("获取巡检计划列表失败", error);
        this.planList = [];
        this.total = 0;
        this.loading = false;
      });
    },
    /** 查询巡检配置列表 */
    getConfigList() {
      return new Promise((resolve, reject) => {
        // 使用巡检配置API
        listInspectionConfig({ configStatus: '1' }).then(response => {
        this.configOptions = (response.rows || []).map(item => {
          return {
            value: item.configId,
            label: item.configName,
            data: item
          };
          });
          resolve(this.configOptions);
        }).catch(error => {
          console.error("获取巡检配置列表失败", error);
          this.configOptions = [];
          reject(error);
        });
      });
    },
    /** 查询设备列表 */
    getEquipmentList() {
      return new Promise((resolve, reject) => {
        listEquipment({ pageSize: 500, pageNum: 1 }).then(response => {
        this.equipmentOptions = (response.rows || []).map(item => {
          return {
            value: item.equipmentId,
            label: item.equipmentName,
            data: item
          };
          });
          resolve(this.equipmentOptions);
        }).catch(error => {
          console.error("获取设备列表失败", error);
          this.equipmentOptions = [];
          reject(error);
        });
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        planId: null,
        planCode: null,
        planName: null,
        configId: null,
        configName: null,
        equipmentId: null,
        equipmentName: null,
        cycleType: "1",
        cycleValue: 1,
        cycleConfigJson: "",
        startDate: null,
        endDate: null,
        inspectorId: null,
        inspectorName: null,
        status: "0",
        autoGenerate: "1",
        deptId: null,
        deptName: null,
        remark: null
      };
      
      this.autoGenerateCodes = true; // 默认启用自动生成编码
      this.planCodeExists = false; // 重置计划编号已存在状态
      
      // 重置周期配置
      this.cycleConfig = {
        weekdays: [],
        monthDays: [],
        quarterMonths: [],
        quarterDays: [],
        yearMonths: [],
        yearDays: [],
        customDates: []
      };
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.planId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 处理配置选择变化 */
    handleConfigChange(configId) {
      console.log("handleConfigChange被调用, configId:", configId);
      // 查找选中的配置项
      const config = this.configOptions.find(option => option.value === configId);
      if (config) {
        this.form.configName = config.label;
        console.log("找到配置项:", config);
      }

      // 如果启用了自动生成编码，则在选择配置后自动生成
      if (this.autoGenerateCodes && configId) {
        this.generatePlanCode();
      }
    },
    /** 设备选择变更 */
    handleEquipmentChange(value) {
      const selectedEquipment = this.equipmentOptions.find(option => option.value === value);
      if (selectedEquipment) {
        this.form.equipmentName = selectedEquipment.label;
        
        // 检查该设备是否已被其他计划使用
        this.checkEquipmentUsage(value);
      }
    },
    /** 检查设备使用情况 */
    checkEquipmentUsage(equipmentId) {
      // 排除当前正在编辑的计划ID
      const excludePlanId = this.form.planId || 0;
      
      // 查询使用该设备的其他计划
      listInspectionPlan({ equipmentId: equipmentId, status: '1' }).then(response => {
        const usedPlans = response.rows.filter(plan => plan.planId !== excludePlanId);
        
        if (usedPlans.length > 0) {
          this.$modal.alertWarning(`注意：该设备已被以下巡检计划使用：${usedPlans.map(p => p.planName).join(', ')}。建议避免重复使用同一设备。`);
        }
      });
    },
    /** 部门选择变更 */
    handleDeptChange(value) {
      const selectedDept = this.deptOptions.find(option => option.deptId === value);
      if (selectedDept) {
        this.form.deptName = selectedDept.deptName;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      console.log("handleAdd被调用");
      this.reset();
      
      // 设置默认值
      const today = new Date();
      this.form.startDate = this.formatDate(today);
      // 不再自动设置结束日期，由用户手动选择
      
      // 默认周期类型为"1"（每天）
      this.form.cycleType = "1";
      
      // 初始化周期值，但不自动计算结束日期
      this.cycleConfig.weekdays = ['1']; // 默认选择周一
      this.form.cycleValue = 1;
      this.form.cycleConfigJson = JSON.stringify({ type: 'daily' });
      
      // 先加载必要数据
      this.loadRequiredData();
      
      // 默认启用自动生成编码
      this.autoGenerateCodes = true;
      
      // 立即打开对话框，数据会异步加载
      this.open = true;
      this.title = "添加巡检计划";
    },
    
    /** 加载设备类型和设备列表 */
    loadRequiredData() {
      // 如果需要加载设备类型
      if (this.configOptions.length === 0) {
        this.getConfigList().catch(error => {
          console.error("加载设备类型失败", error);
        });
      }
      
      // 如果需要加载设备列表
      if (this.equipmentOptions.length === 0) {
        this.getEquipmentList().catch(error => {
          console.error("加载设备列表失败", error);
        });
      }
    },
    /** 生成唯一的计划编号 */
    generatePlanCode() {
      console.log("generatePlanCode被调用");
      
      if (!this.autoGenerateCodes) {
        console.log("自动生成编码已禁用，不生成编码");
        return;
      }
      
      // 如果没有选择巡检配置，则不生成
      if (!this.form.configId) {
        console.log("未选择巡检配置，无法生成编码");
        this.form.planCode = "";
        return;
      }
      
      // 设置加载状态
      const loadingInstance = this.$loading({
        lock: true,
        text: '正在生成计划编号...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      // 调用后端接口获取唯一的计划编号
      return generatePlanCode().then(response => {
        loadingInstance.close();
        if (response && response.data) {
          console.log("获取计划编号成功", response);
          this.form.planCode = response.data;
          
          // 使用多种方法确保表单更新
          this.$set(this.form, 'planCode', response.data);
          
          // 强制更新视图和验证
          this.$nextTick(() => {
            // 触发表单验证
            this.$refs.form.validateField('planCode');
            this.$forceUpdate(); // 强制视图刷新
          });
          
          return response.data;
        } else {
          // 如果获取失败，生成一个带有时间戳的编号作为备选
          this.generateLocalCode();
          return this.form.planCode;
        }
      }).catch(error => {
        loadingInstance.close();
        console.error("获取计划编号失败", error);
        // 获取计划编号失败时的处理
        this.generateLocalCode();
        return this.form.planCode;
      });
    },
    
    /** 本地生成计划编号 */
    generateLocalCode() {
      const now = new Date();
      const dateStr = now.getFullYear().toString().substring(2) + 
            String(now.getMonth() + 1).padStart(2, '0') + 
            String(now.getDate()).padStart(2, '0');
      
      // 生成3位随机数
      const randomCode = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
      
      // 使用PLAN前缀
      this.form.planCode = `PLAN-${dateStr}-${randomCode}`;
      console.log("本地生成的计划编号:", this.form.planCode);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const planId = row.planId || this.ids[0];
      
      // 首先确保配置选项已加载
      const loadConfig = this.configOptions.length > 0 
        ? Promise.resolve(this.configOptions) 
        : this.getConfigList();

      // 首先确保设备选项已加载
      const loadEquipment = this.equipmentOptions.length > 0 
        ? Promise.resolve(this.equipmentOptions) 
        : this.getEquipmentList();

      Promise.all([loadConfig, loadEquipment]).then(() => {
        // 加载数据
        getInspectionPlan(planId).then(response => {
          console.log("获取巡检计划详情:", response.data);
          
          // 检查返回数据结构
          if (response.data && response.data.planInfo) {
            // 新的数据结构，使用planInfo
            this.form = response.data.planInfo;
            console.log("使用新数据结构");
          } else {
            // 旧的数据结构，直接使用response.data
            this.form = response.data;
            console.log("使用旧数据结构");
          }
            
          // 确保巡检配置选择正确
          this.matchConfigName();
          
          // 初始化周期配置
          this.initCycleConfig();
          
          this.open = true;
          this.title = "修改巡检计划";
        });
      }).catch(error => {
        console.error("加载数据失败", error);
        this.$message.error("加载数据失败，请重试");
      });
    },
    
    /** 匹配巡检配置名称 */
    matchConfigName() {
      // 确保configOptions已加载
      if (this.configOptions.length === 0) {
        return this.getConfigList().then(() => this.matchConfigName());
      }
      
      if (this.form.configId) {
        const config = this.configOptions.find(item => Number(item.value) === Number(this.form.configId));
        if (config) {
          this.form.configName = config.label;
          console.log("成功匹配到配置名称:", this.form.configName);
        } else {
          console.log("找不到对应的配置，configId:", this.form.configId, "所有配置:", this.configOptions);
        }
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 确保cycleValue是整数类型
          this.form.cycleValue = parseInt(this.form.cycleValue) || 1;
          
          if (this.form.planId != null) {
            updateInspectionPlan(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            if (this.autoGenerateCodes && !this.form.planCode) {
              this.$modal.msgError("计划编号生成失败，请稍后再试");
              return;
            }
            
            // 先检查计划编号是否唯一
            if (this.planCodeExists) {
              this.$modal.msgError("计划编号已存在，请更换");
              return;
            }
            
            addInspectionPlan(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const planIds = row.planId || this.ids;
      this.$modal.confirm('确认删除所选的巡检计划吗？').then(function() {
        return deleteInspectionPlan(planIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 状态修改 */
    handleStatusChange(row) {
      let text = row.status === "0" ? "停用" : "启用";
      this.$modal.confirm('确认要"' + text + '""' + row.planName + '"吗？').then(function() {
        return updateInspectionPlanStatus(row.planId, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(() => {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    /** 查看详情按钮操作 */
    handleDetail(row) {
      this.$router.push({ path: '/sb/inspection-plan/detail/' + row.planId });
    },
    /** 生成巡检单按钮操作 */
    handleCreateRecord(row) {
      this.$modal.confirm('确认要为"' + row.planName + '"生成巡检单吗？').then(function() {
        return generateInspectionRecord(row.planId);
      }).then(response => {
        this.$modal.msgSuccess("巡检单生成成功");
        // 添加延迟，确保后端处理完成
        setTimeout(() => {
        this.handleViewRecords(row);
        }, 500);
      }).catch(error => {
        console.error('生成巡检单失败:', error);
        this.$modal.msgError('生成巡检单失败: ' + (error.message || '未知错误'));
      });
    },
    /** 查看巡检记录按钮操作 */
    handleViewRecords(row) {
      this.recordsLoading = true;
      this.currentPlanId = row.planId;
      listInspectionRecord({ planId: row.planId, pageSize: 100 }).then(response => {
        this.recordsList = response.rows || [];
        this.recordsLoading = false;
        this.recordsDialogVisible = true;
      });
    },
    /** 查看巡检记录详情按钮操作 */
    handleViewRecord(row) {
      this.$router.push({ path: '/sb/inspection-record/detail/' + row.recordId });
    },
    /** 打开用户选择对话框 */
    showUserSelect() {
      this.userDialogVisible = true;
      this.getUserList();
    },
    /** 获取用户列表 */
    getUserList() {
      this.userListLoading = true;
      
      // 构建查询参数
      const params = {
        pageNum: this.userQueryParams.pageNum,
        pageSize: this.userQueryParams.pageSize
      };
      
      // 添加查询条件
      if (this.userQueryParams.userName) {
        params.userName = this.userQueryParams.userName;
      }
      
      if (this.userQueryParams.nickName) {
        params.nickName = this.userQueryParams.nickName;
      }
      
      console.log("查询用户参数:", params);
      
      // 调用API查询用户
      listUser(params).then(response => {
        console.log("获取到的用户列表数据:", response);
        
        if (response.rows && response.rows.length > 0) {
          // 确保每个用户都有部门信息
          this.userList = response.rows.map(user => {
            // 处理部门信息
            if (user.dept && user.dept.deptName && !user.deptName) {
              user.deptName = user.dept.deptName;
            }
            return user;
          });
          
          this.userTotal = response.total || 0;
        } else {
          this.userList = [];
          this.userTotal = 0;
        }
        
        this.userListLoading = false;
      }).catch(error => {
        console.error("获取用户列表失败", error);
        this.userList = [];
        this.userTotal = 0;
        this.userListLoading = false;
      });
    },
    
    /** 用户查询按钮操作 */
    handleUserQuery() {
      this.userQueryParams.pageNum = 1;
      this.getUserList();
    },
    
    /** 重置用户查询按钮操作 */
    resetUserQuery() {
      this.$refs.userQueryForm.resetFields();
      
      // 重置查询参数
      this.userQueryParams = {
        pageNum: 1,
        pageSize: 10,
        userName: '',
        nickName: ''
      };
      
      // 重新查询
      this.getUserList();
    },
    /** 用户表行点击事件 */
    handleUserRowClick(row) {
      this.selectedUser = row;
    },
    /** 确认选择用户 */
    confirmUserSelect() {
      if (!this.selectedUser) {
        this.$modal.msgError("请选择一个用户");
        return;
      }
      
      this.form.inspectorId = this.selectedUser.userId;
      this.form.inspectorName = this.selectedUser.nickName;
      
      // 处理部门信息
      if (this.selectedUser.dept && this.selectedUser.dept.deptId) {
        this.form.deptId = this.selectedUser.dept.deptId;
        this.form.deptName = this.selectedUser.dept.deptName;
      } else {
      this.form.deptId = this.selectedUser.deptId;
        this.form.deptName = this.selectedUser.deptName || '未分配';
      }
      
      this.userDialogVisible = false;
    },
    /** 取消选择用户 */
    cancelUserSelect() {
      this.userDialogVisible = false;
      this.selectedUser = null;
    },
    /** 处理用户选择变化 */
    handleUserChange(userId) {
      if (userId) {
        const selectedUser = this.userOptions.find(user => user.userId === userId);
        if (selectedUser) {
          this.form.inspectorName = selectedUser.nickName;
        }
      } else {
        this.form.inspectorName = '';
      }
    },
    /** 格式化日期为yyyy-MM-dd */
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    /** 处理自动生成编码复选框变化 */
    handleAutoGenerateCodesChange(value) {
      this.autoGenerateCodes = value;
      if (value) {
        this.form.planCode = ""; // 清空手动输入的编号
        this.planCodeExists = false; // 确保不存在状态为false
        
        // 如果已选择了巡检配置，立即生成编号
        if (this.form.configId) {
          this.generatePlanCode();
        }
      }
    },
    /** 强制重新生成计划编号 */
    forceGenerateCode() {
      this.generatePlanCode();
    },
    /**
     * 检查计划编号是否存在
     */
    checkPlanCodeExist() {
      // 只有当不是自动生成且输入了值时才检查
      if (!this.autoGenerateCodes && this.form.planCode) {
        checkPlanCodeUnique(this.form.planCode).then(response => {
          if (!response.data) {
            this.planCodeExists = true;
            this.$modal.msgError("计划编号已存在，请更换");
          } else {
            this.planCodeExists = false;
          }
        });
      }
    },
    /** 
     * 更新周期值，将配置转换为JSON字符串存储 
     */
    updateCycleValue() {
      // 根据当前cycleType获取对应的配置
      let configValue = {};
      let numValue = 1; // 默认数值为1
      
      switch (this.form.cycleType) {
        case '1': // 每天
          configValue = { type: 'daily' };
          numValue = 1;
          break;
        case '2': // 每周
          configValue = { 
            type: 'weekly', 
            weekdays: this.cycleConfig.weekdays 
          };
          // 如果选择了周几，设置为周几数量，否则默认为1
          numValue = this.cycleConfig.weekdays.length > 0 ? this.cycleConfig.weekdays.length : 1;
          break;
        case '3': // 每月
          configValue = { 
            type: 'monthly', 
            days: this.cycleConfig.monthDays 
          };
          // 设置为选择的天数，默认为1
          numValue = this.cycleConfig.monthDays.length > 0 ? this.cycleConfig.monthDays.length : 1;
          break;
        case '4': // 每季度
          configValue = { 
            type: 'quarterly', 
            months: this.cycleConfig.quarterMonths,
            days: this.cycleConfig.quarterDays
          };
          // 季度设置为3
          numValue = 3;
          break;
        case '5': // 每年
          configValue = { 
            type: 'yearly', 
            months: this.cycleConfig.yearMonths,
            days: this.cycleConfig.yearDays
          };
          // 年度设置为12
          numValue = 12;
          break;
        case '6': // 自定义
          configValue = { 
            type: 'custom', 
            dates: this.cycleConfig.customDates 
          };
          // 自定义设置为日期数量
          numValue = this.cycleConfig.customDates ? this.cycleConfig.customDates.length : 1;
          break;
      }
      
      // 将配置转换为JSON字符串存储到额外的字段
      this.form.cycleConfigJson = JSON.stringify(configValue);
      
      // cycleValue保持为数字类型
      this.form.cycleValue = numValue;
      
      // 不再自动计算结束日期，由用户手动选择
      console.log("周期值已更新，cycleType:", this.form.cycleType, "cycleValue:", numValue);
    },
    
    /** 
     * 处理周期类型改变 
     */
    handleCycleTypeChange(cycleType) {
      // 根据周期类型设置默认值
      switch (cycleType) {
        case '1': // 每天
          break;
        case '2': // 每周
          if (!this.cycleConfig.weekdays.length) {
            this.cycleConfig.weekdays = ['1']; // 默认选择周一
          }
          break;
        case '3': // 每月
          if (!this.cycleConfig.monthDays.length) {
            this.cycleConfig.monthDays = [1]; // 默认选择每月1号
          }
          break;
        case '4': // 每季度
          if (!this.cycleConfig.quarterMonths.length) {
            this.cycleConfig.quarterMonths = ['1']; // 默认选择第一个月
          }
          if (!this.cycleConfig.quarterDays.length) {
            this.cycleConfig.quarterDays = [1]; // 默认选择1号
          }
          break;
        case '5': // 每年
          if (!this.cycleConfig.yearMonths.length) {
            this.cycleConfig.yearMonths = ['1']; // 默认选择1月
          }
          if (!this.cycleConfig.yearDays.length) {
            this.cycleConfig.yearDays = [1]; // 默认选择1号
          }
          break;
        case '6': // 自定义
          if (!this.cycleConfig.customDates || !this.cycleConfig.customDates.length) {
            // 默认添加明天作为执行日期
            const tomorrow = new Date();
            tomorrow.setDate(tomorrow.getDate() + 1);
            this.cycleConfig.customDates = [this.formatDate(tomorrow)];
          }
          break;
      }
      
      // 更新周期值
      this.updateCycleValue();
    },
    
    /** 
     * 根据周期类型计算结束日期 
     */
    calculateEndDate() {
      // 如果没有开始日期，则不自动计算
      if (!this.form.startDate) {
        return;
      }
      
      // 获取开始日期
      const startDate = new Date(this.form.startDate);
      let endDate = new Date(startDate);
      
      // 根据周期类型计算结束日期
      switch (this.form.cycleType) {
        case '1': // 每天
          endDate.setDate(startDate.getDate() + 30); // 默认30天
          break;
        case '2': // 每周
          endDate.setDate(startDate.getDate() + 90); // 默认13周(约3个月)
          break;
        case '3': // 每月
          endDate.setMonth(startDate.getMonth() + 6); // 默认6个月
          break;
        case '4': // 每季度
          endDate.setMonth(startDate.getMonth() + 12); // 默认4个季度(1年)
          break;
        case '5': // 每年
          endDate.setFullYear(startDate.getFullYear() + 2); // 默认2年
          break;
        case '6': // 自定义
          if (this.cycleConfig.customDates && this.cycleConfig.customDates.length) {
            // 获取自定义日期中的最后一天作为结束日期
            const sortedDates = [...this.cycleConfig.customDates].sort();
            endDate = new Date(sortedDates[sortedDates.length - 1]);
          } else {
            // 默认1个月后
            endDate.setMonth(startDate.getMonth() + 1);
          }
          break;
      }
      
      // 格式化日期并设置到表单中
      this.form.endDate = this.formatDate(endDate);
    },
    
    /** 
     * 初始化周期配置 - 从现有数据解析 
     */
    initCycleConfig() {
      // 如果有配置JSON数据，从cycleConfigJson加载
      if (this.form.cycleConfigJson) {
        try {
          const config = JSON.parse(this.form.cycleConfigJson);
          
          switch (this.form.cycleType) {
            case '2': // 每周
              this.cycleConfig.weekdays = config.weekdays || [];
              break;
            case '3': // 每月
              this.cycleConfig.monthDays = config.days || [];
              break;
            case '4': // 每季度
              this.cycleConfig.quarterMonths = config.months || [];
              this.cycleConfig.quarterDays = config.days || [];
              break;
            case '5': // 每年
              this.cycleConfig.yearMonths = config.months || [];
              this.cycleConfig.yearDays = config.days || [];
              break;
            case '6': // 自定义
              this.cycleConfig.customDates = config.dates || [];
              break;
          }
        } catch (e) {
          console.error("解析周期配置失败:", e);
        }
      }
      // 如果没有配置数据，则使用默认值
      else {
        this.handleCycleTypeChange(this.form.cycleType);
      }
    },
    /** 开始日期变更处理 */
    handleStartDateChange(val) {
      // 移除自动设置结束日期的逻辑，改为由用户手动选择
      console.log("开始日期已更改:", val);
      // 不再自动设置结束日期
    },
    /** 处理更多操作命令 */
    handleCommand(command, row) {
      if (command === 'generate') {
        this.handleCreateRecord(row);
      } else if (command === 'viewRecords') {
        this.handleViewRecords(row);
      }
    }
  }
};
</script> 

<style scoped>
.el-dropdown-menu {
  padding: 0;
}

.el-dropdown-item {
  font-size: 14px;
  padding: 8px 16px;
  cursor: pointer;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.inspection-cycle-container {
  position: relative;
  padding: 20px;
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  margin-bottom: 10px;
}

.help-icon {
  position: absolute;
  top: 10px;
  right: 10px;
  font-size: 16px;
  color: #909399;
  cursor: pointer;
}

.help-icon:hover {
  color: #409EFF;
}

.cycle-type-selector {
  margin-bottom: 20px;
}

.cycle-config {
  margin-top: 10px;
  padding: 10px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
}

.cycle-label {
  display: inline-block;
  width: 120px;
  margin-right: 10px;
}

.cycle-desc {
  color: #606266;
  font-style: italic;
}

.year-month-checkboxes {
  display: flex;
  flex-wrap: wrap;
}

.year-month-checkboxes .el-checkbox {
  margin-right: 10px;
  margin-bottom: 5px;
}
</style> 